import React, { useEffect, useRef, useState } from 'react';
import videojs from "video.js";
import "video.js/dist/video-js.css";
import { Mask } from 'antd-mobile';
import {
  CaretRightOutlined,
} from '@ant-design/icons';

const VideoJS = ( props ) => {
  const videoRef = useRef(null);
  const playerRef = useRef(null);
  const { options, onReady } = props;

  const addDefinitionTool = (player) => {
    const self = this
    // 初始化清晰度按钮
    const TextTrackMenuItem = videojs.getComponent('TextTrackMenuItem')
    const TrackButton = videojs.getComponent('TrackButton')
    // 扩展基类，实现菜单项事件
    const QualityTrackItem = videojs.extend(TextTrackMenuItem, {
      // 切换高清播放源，this 指向被点击QualityTrackItem实例
      handleClick(event) {
        // 先将所有选项的选中状态设为未选中
        this.parentComponent_.children_.forEach((c) => {
          c.selected(false)
        })
        // 选中当前
        this.selected(true)
        // 选中后修改按钮文本
        self.qualityBtn.children()[0].el().firstElementChild.innerText = this.track.value
        // 其他逻辑
      },
    })
    // 扩展基类，实现菜单按钮
    const QualityTrackButton = videojs.extend(TrackButton, {
      constructor() {
        TrackButton.apply(this, arguments)
        this.controlText('Switch Quality')
      },
      createItems() {
        const videoQuality = '360p,480p,1080p';
        const qualityKeyArray = videoQuality.split(',')
        if (qualityKeyArray.length > 0) {
          const result = []
          qualityKeyArray.forEach((key) => {
            result.push(
              new QualityTrackItem(this.player_, {
                track: {
                  label: key,
                  value: key,
                },
                selectable: true,
              })
            )
          })
          return result
        } else {
          return []
        }
      }
    })
    const qualityBtn = new QualityTrackButton(player, {})
    // 默认展示360p视频
    qualityBtn.children()[0].el().firstElementChild.innerText = '360p'
    player.controlBar.addChild(qualityBtn, {}, 10)
  }

  useEffect(() => {
    // make sure Video.js player is only initialized once
    if (!playerRef.current) {
      const videoElement = videoRef.current;
      if (!videoElement) return;
      const player = playerRef.current = videojs(videoElement, options, () => {
        console.log("player is ready");
        onReady && onReady(player);
      });
      // 新增清晰度按钮
      // addDefinitionTool(player);
    } else {
      // you can update player here [update player through props]
      const player = playerRef.current;
      console.log('playerplayerplayer===',player);
      player.src(options.sources[0].src);      
      player.autoplay(true);
    }
  }, [options, videoRef]);

  return (
    <div className='video-inner'>
      <video ref={videoRef} className="video-js vjs-big-play-centered vjs-fluid" disablePictureInPicture/>
    </div>
  );
}

const Content = ({ dataSource, isMobile, ...props }) => {
  const [visible, setVisible] = useState(false);
  useEffect(() => {

  },[])

  const playVideo = () => {
    setVisible(true);
  }

  return (
    <div className="content5-wrapper">
      <div className="c-grid-layout">
        <div className="content5-title">
          <span>新一代云原生实时数据湖引领者</span>
        </div>
        <div className='content5-video'>
          <img src='https://sfservices.obs.cn-south-1.myhuaweicloud.com/sdp-web/startshinex/computer.png'></img>
          <div className='player-button' onClick={playVideo}>
            <CaretRightOutlined style={{color:'#fff',fontSize:'25px'}}/>
          </div>
        </div>
      </div>
      <Mask visible={visible} destroyOnClose onMaskClick={() => setVisible(false)}>
        <div className='videojs-container'>
          <VideoJS
            options={{
              controls: true,
              playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
              //autoplay: true, // 如果true,浏览器准备好时开始回放。
              muted: false, // 默认情况下将会消除任何音频。
              loop: false, // 视频一结束就重新开始。
              preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
              language: 'zh-CN',
              aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
              //fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
              sources: [
                {
                  src: 'https://sfservices.obs.cn-south-1.myhuaweicloud.com/sdp-web/startshinex/starshinex_video_small.mp4',
                  type: 'video/mp4'
                }
              ],
              // poster: 'https://sfservices.obs.cn-south-1.myhuaweicloud.com/sdp-web/startshinex/video-poster.png', // 你的封面地址
              notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
              controlBar: {
                timeDivider: true,
                durationDisplay: true,
                remainingTimeDisplay: true,
                fullscreenToggle: true, // 全屏按钮
                volumePanel: {
                  inline: false,
                }
              }
            }}
            onReady={(play)=>{
              play.play()
            }}
          />
        </div>
      </Mask>
    </div>
  );
}

export default Content;
